<template>
  <div id="app">
    <router-view />
    <Setings ref="setingsRef" />
  </div>
</template>

<script>
import setIntroduction from '@/utils/setIconfont.js'
import { Local } from '@/utils/storage.js'
import Setings from '@/layout/navBars/breadcrumb/setings.vue'
import { Session } from './utils/storage'
import { getSystemInfoConfig } from './api/system/config'

export default {
  name: 'App',
  components: { Setings },
  watch: {
    // 监听路由的变化
    $route: {
      handler(to) {
        this.$nextTick(() => {
          let webTitle = ''
          let { globalTitle } = this.$store.state.themeConfig.themeConfig
          to.path === '/login'
            ? (webTitle = to.meta.title)
            : (webTitle = this.$t(to.meta.title))
          document.title = `${webTitle}` || globalTitle
        })
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.initSetIconfont()
    this.openSetingsDrawer()
    this.getLayoutThemeConfig()
  },
  destroyed() {
    this.bus.$off('openSetingsDrawer')
  },
  methods: {
    // 设置初始化，防止刷新时恢复默认
    initSetIconfont() {
      // 设置批量第三方 icon 图标
      setIntroduction.cssCdn()
      // 设置批量第三方 js
      setIntroduction.jsCdn()
    },
    // 布局配置弹窗打开
    openSetingsDrawer() {
      this.bus.$on('openSetingsDrawer', () => {
        this.$refs.setingsRef.openDrawer()
      })
    },
    // 获取缓存中的布局配置
    getLayoutThemeConfig() {
      let themeConfigPrev = Local.get('themeConfigPrev')
      if (themeConfigPrev) {
        this.getWebGlobalInfo(themeConfigPrev).then((res) => {
          this.$store.dispatch('themeConfig/setThemeConfig', res)
        })
        document.documentElement.style.cssText = Local.get('themeConfigStyle')
      } else {
        this.getWebGlobalInfo(this.$store.state.themeConfig.themeConfig).then(
          (res) => {
            Local.set('themeConfigPrev', res)
          }
        )
      }
    },
    // 拉取网站配置信息
    async getWebGlobalInfo(themeConfigPrev) {
      // 临时存储 避免重复请求
      let globalConfigInfo = Session.get('globalConfigInfo')
      if (!globalConfigInfo) {
        let res = await getSystemInfoConfig()
        globalConfigInfo = JSON.parse(res.data)
        Session.set('globalConfigInfo', globalConfigInfo)
      }
      let { name, logoImg } = globalConfigInfo
      themeConfigPrev.globalTitle = name
      themeConfigPrev.globalLogo = logoImg
      themeConfigPrev.copyright = globalConfigInfo.copyright
      console.log(themeConfigPrev)
      return themeConfigPrev
    }
  }
}
</script>
<style lang="scss">
.cp {
  cursor: pointer;
}
.el-scrollbar {
  > .el-scrollbar__bar {
    opacity: 1 !important;
  }
}
</style>
